<script setup lang="ts">
import { showToast, removeStorage, reLaunch } from '@tarojs/taro';
import { ref, onMounted } from 'vue';
import JSEncrypt from 'jsencrypt';
import { cloneDeep } from 'lodash';
import { GET_PUBLIC_KEY } from '/@/api/modules/open-api/auth';
import { LOGIN_APP, UPDATE_PWD_APP2 } from '/@/api/modules/base/app-sys-user';
import { formState, formRules } from './state';

const updatePasswordFormRef = ref();
const RSA = new JSEncrypt();

/**
 * @function 确认登录
 */
function submit() {
  updatePasswordFormRef.value.validate().then(({ valid }) => {
    if (!valid) return;

    GET_PUBLIC_KEY({ secretTag: 'ib_platform_pub' }).then((res1) => {
      const _form = cloneDeep(formState);
      RSA.setPrivateKey(res1.publicKey);
      _form.newPwd = RSA.encrypt(`${Date.now()}${formState.newPwd}`) as string;
      _form.repeatNewPwd = RSA.encrypt(`${Date.now()}${formState.repeatNewPwd}`) as string;

      UPDATE_PWD_APP2(_form).then(() => {
        formState.newPwd = '';
        formState.repeatNewPwd = '';

        showToast({
          title: '修改密码成功！将退出登录',
          icon: 'success',
          duration: 3000,
        });

        setTimeout(() => {
          removeStorage({
            key: 'token',
            success: () => {
              reLaunch({ url: '/pages/user/login/index' });
            },
          });
        }, 3000);
      });
    });
  });
}

onMounted(() => {
  LOGIN_APP().then((res) => {
    formState.uaaUserId = res.sysUserDto.uaaUserId || '';
  });
});
</script>

<template>
  <view class="update-password app-page--1">
    <app-navbar title="修改密码" />
    <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
      <view class="update-password__wrapper">
        <nut-form
          :model-value="formState"
          :rules="formRules"
          class="update-password__form"
          ref="updatePasswordFormRef"
        >
          <nut-form-item
            required
            label="新密码"
            prop="newPwd"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              v-model="formState.newPwd"
              placeholder="请输入新密码"
              type="password"
              :border="false"
              clearable
            />
          </nut-form-item>
          <nut-form-item
            required
            label="确认新密码"
            prop="repeatNewPwd"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              v-model="formState.repeatNewPwd"
              placeholder="请确认新密码"
              type="password"
              :border="false"
              clearable
            />
          </nut-form-item>
        </nut-form>
        <nut-button class="update-password__submit-btn" type="info" block @click="submit()">
          修改
        </nut-button>
      </view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
